import BaseVenueProcessor from './BaseVenueProcessor.js';
import { getFengTaiHuaYuanVenueSettings } from '../request.js';

/**
 * 丰泰花园网球场数据处理器
 */
export class FengTaiHuaYuanProcessor extends BaseVenueProcessor {
  constructor() {
    super();
    this.venueName = '丰泰花园网球场';
    this.timeSlots = [
      '7:00-8:00', '8:00-9:00', '9:00-10:00', '10:00-11:00', '11:00-12:00',
      '12:00-13:00', '13:00-14:00', '14:00-15:00', '15:00-16:00', '16:00-17:00',
      '17:00-18:00', '18:00-19:00', '19:00-20:00', '20:00-21:00', '21:00-22:00'
    ];
  }

  /**
   * 获取丰泰花园网球场预约设置
   * @param {Object} params - 查询参数 { startDate, endDate }
   * @returns {Promise} 请求Promise
   */
  async getVenueSettings(params = {}) {
    // 设置默认参数
    const today = new Date();
    const tomorrow = new Date(today.getTime() + 24 * 60 * 60 * 1000);
    
    // 格式化为指定格式：Wed Oct 15 2025 00:00:00 GMT+0800 (中国标准时间)
    const formatDate = (date) => {
      return date.toString();
    };
    
    const defaultParams = {
      startDate: formatDate(today),
      endDate: formatDate(tomorrow)
    };
    // 合并参数
    const requestData = { ...defaultParams, ...params };
    
    return await getFengTaiHuaYuanVenueSettings(requestData);
  }

  /**
   * 验证数据是否有效
   * @param {Object} data - 原始场地数据
   * @returns {boolean} 数据是否有效
   */
   validateData(data) {
    return data && 
           data.data && 
           data.data.data && 
           Array.isArray(data.data.data.courtList);
  }
  
  /**
   * 将场地数据按场地名称分组
   * @param {Object} data - 原始场地数据
   * @returns {Map} 按场地名称分组的数据
   */
  groupVenues(data) {
    const venueMap = new Map();
    
    // 根据courtList数据创建场地分组
    data.data.data.courtList.forEach(court => {
      const venueName = court.subClassroomName || `${court.number}号场`;
      if (!venueMap.has(venueName)) {
        venueMap.set(venueName, {
          name: venueName,
          dataSource: this.venueName,
          timeSlots: [],
          courtId: court.number,
          maxPeople: 4, // 网球场默认4人
          pic: '', // 可以后续添加图片
          subClassroomNumber: court.number
        });
      }
    });
    
    return venueMap;
  }

  /**
   * 处理时间段数据
   * @param {Map} venueMap - 按场地分组的数据
   * @param {Object} data - 原始数据
   */
  processTimeSlots(venueMap, data) {
    // 定义时间段，从7:00到22:00，每小时一个时间段
    const timeSlots = [];
    for (let hour = 7; hour <= 21; hour++) {
      const startTime = `${hour.toString().padStart(2, '0')}:00`;
      const endTime = `${(hour + 1).toString().padStart(2, '0')}:00`;
      timeSlots.push({
        time: `${startTime}-${endTime}`,
        startHour: hour,
        endHour: hour + 1
      });
    }

    // 遍历每个场地
    data.data.data.courtList.forEach(court => {
      const venueName = court.subClassroomName || `${court.number}号场`;
      const venue = venueMap.get(venueName);
      
      if (venue && court.list && Array.isArray(court.list)) {
        // 为每个时间段添加时间槽信息
        timeSlots.forEach((timeSlot, index) => {
          // 获取对应索引的API数据，如果没有则设为不可用
          const apiSlot = court.list[index];
          
          let isFree = false;
          let price = 0;
          let remark = '';
          
          if (apiSlot) {
            // status为0表示可预约
            isFree = apiSlot.status === 0;
            // 价格除以100转换为元
            price = apiSlot.price / 100;
            remark = apiSlot.isMakeAppointment ? '需预约' : '';
          }
          
          const beginDatetime = `${this.selectedDate} ${timeSlot.time.split('-')[0]}`;
          const endDatetime = `${this.selectedDate} ${timeSlot.time.split('-')[1]}`;
          
          venue.timeSlots.push({
            time: timeSlot.time,
            isFree: isFree,
            price: price,
            beginDatetime: beginDatetime,
            endDatetime: endDatetime,
            resourceId: apiSlot ? apiSlot.id : null,
            remark: remark
          });
        });
      }
    });
  }

  /**
   * 将分组后的场地数据转换为列表格式
   * @param {Map} venueMap - 按场地分组的数据
   * @returns {Array} 场地列表
   */
  convertToVenueList(venueMap) {
    const venues = [];
    
    venueMap.forEach((venue, venueName) => {
      // 只添加有时间槽的场地
      if (venue.timeSlots.length > 0) {
        venues.push({
          name: venueName,
          dataSource: venue.dataSource,
          timeSlots: venue.timeSlots,
          courtId: venue.courtId,
          maxPeople: venue.maxPeople,
          pic: venue.pic,
          subClassroomNumber: venue.subClassroomNumber
        });
      }
    });
    
    return venues;
  }

  /**
   * 处理场地数据
   * @param {Object} data - 原始场地数据
   * @param {Date} selectedDate - 选择的日期
   * @returns {Array} 处理后的场地列表
   */
 process(data, selectedDate) {
    this.selectedDate = selectedDate;
    
    if (!this.validateData(data)) {
      console.warn('丰泰花园网球场数据验证失败:', data);
      return [];
    }

    const venueMap = this.groupVenues(data);
    this.processTimeSlots(venueMap, data);
    console.log("丰泰花园网球场数据:", data);
    
    return this.convertToVenueList(venueMap);
  }
}

export default FengTaiHuaYuanProcessor;